package com.sjn.common.response;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author EDZ
 */
@Schema(description = "")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Page {

    /**
     * 每一页记录数
     */
    @Schema(description = "每一页记录数")
    @Min(value = 0)
    private Integer pageSize = 10;
    /**
     * 当前第几页
     */
    @Schema(description = "当前第几页")
    @Min(value = 0)
    private Integer pageIndex = 1;
    /**
     * 最后一页下标/记录总页数
     */
    @Schema(description = "最后一页下标/记录总页数")
    private Integer lastPageIndex = 0;
    /**
     * 记录开始下标
     */
    @Schema(description = "记录开始下标")
    private Long start = 1L;

    /**
     * 记录开始下标
     */
    @Schema(description = "记录开始下标")
    private Long end = 0L;
    /**
     * 总共记录数
     */
    @Schema(description = "总共记录数")
    private Long total = 0L;

    public void config(long total) {
        if (total == 0L) {
            clear();
            return;
        }
        this.total = total;
        lastPageIndex = (int) (total % pageSize == 0 ? (total / pageSize)
                : (total / pageSize + 1));
        if (pageIndex > lastPageIndex) {
            pageIndex = lastPageIndex;
        }
        if (pageIndex < 1) {
            pageIndex = 1;
        }
        start = (long) pageSize * (pageIndex - 1);
        end = start + pageSize;
    }

    public void clear() {
        pageIndex = 1;
        lastPageIndex = 0;
        start = 0L;
        total = 0L;
    }

    public Page(@Min(value = 0) Integer pageIndex, @Min(value = 0) Integer pageSize, Long total) {
        this.pageSize = pageSize;
        this.pageIndex = pageIndex;
        this.config(total);
    }

    public Page(Long total, PageDTO selectRequest) {
        this.pageSize = selectRequest.getPageSize();
        this.pageIndex = selectRequest.getPageIndex();
        this.config(total);
    }

    public Page(PageDTO selectRequest, Long total) {
        this.pageSize = selectRequest.getPageSize();
        this.pageIndex = selectRequest.getPageIndex();
        this.config(total);
    }
}
